package com.action.mvc.ssh.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by Wuxiang on 2017/4/10.
 *
 * 登陆 http://localhost:8080/login?username=admin&password=admin
 */
@SessionAttributes({
        "userid",
        "username"
})
@Controller
public class LoginController {

    @RequestMapping("/login")
    public String doLogin(String username, String password, Model model) {
        if (username.equals("admin") && password.equals("admin")) {
            String userId = "No.1";
            System.out.println("Welcome to Person Infomation System!");
            return "redirect:frame/"+userId+"/"+username;
        }
        return "redirect:error";
    }

    // todo 退出 删除cookies
    @RequestMapping("/logout")
    public String toIndex(ModelMap model, HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.removeAttribute("userid");
        session.removeAttribute("username");
        model.remove("userid");
        model.remove("username");
        return "redirect:/";
    }

    @RequestMapping("/frame/{userId}/{username}")
    public String frame(@PathVariable String userId,
                        @PathVariable String username, Model model) {
        model.addAttribute("userid", userId);
        model.addAttribute("username", username);
        return "frame";
    }

    @RequestMapping("/error")
    public String error() {
        return "error";
    }
}
